<template>
  <el-dialog
    v-el-drag-dialog
    title="新增出库单"
    :visible.sync="visible"
    width="1100px"
    @closed="reset"
  >
    <el-form
      ref="dataForm"
      :inline="true"
      label-width="100px"
      :model="temp"
      :rules="rules"
    >
      <el-form-item label="出库类型">
        <el-select v-model="temp.stockOutType" placeholder="请选择" clearable disabled>
          <el-option
            v-for="item in stockOutTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="调出仓库" prop="storeId">
        <el-select v-model="temp.storeId" placeholder="请选择" clearable @change="outChange">
          <el-option
            v-for="item in leftStoreMap"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="0.3">
        <el-button
          circle
          type="primary"
        ><svg-icon
          class="map"
          icon-class="exchange"
          @click="exchange"
        /></el-button>
      </el-form-item>
      <el-form-item label="调入仓库" prop="targetStoreId">
        <el-select v-model="temp.targetStoreId" placeholder="请选择" clearable @change="inChange">
          <el-option
            v-for="item in rightStoreMap"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="调拨车辆" prop="carNumber">
        <el-select v-model="temp.carNumber" placeholder="请选择" clearable filterable @change="truckChange">
          <el-option
            v-for="item in truckMap"
            :key="item.truckId"
            :label="item.truckCode"
            :value="item.truckId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="司机" prop="operatorId">
        <el-select v-model="temp.operatorId" placeholder="请选择" clearable filterable @change="driverChange">
          <el-option
            v-for="item in driverMap"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" label-width="145px">
        <el-input
          v-model="temp.remark"
          placeholder="请输入"
          clearable
          maxlength="100"
          show-word-limit
          type="textarea"
          resize="none"
          style="width: 200px;"
        />
      </el-form-item>
    </el-form>

    <el-row :gutter="10">
      <el-col :span="6">
        <lb-table
          ref="lbTableLeft"
          border
          class="leftTable"
          highlight-current-row
          element-loading-text="加载中"
          :column="tableLeftData.column"
          :data="tableLeftData.data"
          @current-change="tableLeftChange"
        />
      </el-col>
      <el-col :span="18">
        <lb-table
          ref="lbTableRight"
          border
          class="rightTable"
          element-loading-text="加载中"
          :column="tableRightData.column"
          :data="tableRightData.data"
        />
      </el-col>
    </el-row>
    <div class="total">本次出库<span v-for="(item,index) in sumObj" v-show="item.sum" :key="index">{{ `${item.name}瓶小计${item.sum}，` }}</span>合计{{ allSum }}瓶</div>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="$loadingPlugin.add" type="primary" @click="save">保存</el-button>
      <el-button @click="visible = false">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { formatColumnMap } from '@/utils'
  import { goodsTypeQueryAllList, addStockOutBill, goodsSortList } from '@/api'

  const JINJIANG = 58 // 晋江城市标识

  export default {
    name: 'addOutStorage',
    props: {
      stockOutTypeMap: {
        type: Array,
        required: true
      },
      storeMap: {
        type: Array,
        required: true
      },
      storageStoreMap: {
        type: Array,
        required: true
      },
      truckMap: {
        type: Array,
        required: true
      },
      driverMap: {
        type: Array,
        required: true
      },
      gdStatusMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        temp: {
          stockOutType: 1,
          storeId: '',
          targetStoreId: '',
          carNumber: '',
          operatorId: '',
          remark: ''
        },
        sumObj: [],
        allSum: 0,
        leftStoreMap: [],
        rightStoreMap: [],
        goodsName: '',
        goodsData: {}, // 商品分类数据
        lbTableRightwidth: 14,
        rules: {
          storeId: [{ required: true, message: '请选择调出仓库', trigger: 'blur' }],
          targetStoreId: [{ required: true, message: '请选择调入仓库', trigger: 'change' }],
          carNumber: [{ required: true, message: '请选择调拨车辆', trigger: 'change' }],
          operatorId: [{ required: true, message: '请选择司机', trigger: 'change' }]
        },
        // 左侧列表
        tableLeftData: {
          column: [
            {
              prop: 'goodsName',
              label: '商品名称'
            },
            {
              prop: 'specName',
              label: '规格型号'
            }
          ],
          data: []
        },
        // 右侧列表
        tableRightData: {
          column: [
            {
              prop: 'goodsName',
              label: '商品名称',
              width: 120
            },
            {
              prop: 'goodsSpec',
              label: '规格型号',
              width: 120
            },
            {
              prop: 'gdStatus',
              label: '状态',
              render: (h, scope) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <el-select
                      value={scope.row[scope.column.property]}
                      style='width: 120px'
                      onChange={(val) => {
                        scope.row[scope.column.property] = val
                      }}
                    >
                      {scope.row.gdStatusMap.map((option) => {
                        return (
                          <el-option label={option.desc} value={option.value}></el-option>
                        )
                      })}
                    </el-select>
                  ) : (
                    <span>
                      {scope.row[scope.column.property] &&
                        formatColumnMap(
                          this.transStatusMap,
                          'value',
                          scope.row[scope.column.property],
                          'desc'
                        )}
                    </span>
                  )}
                </div>
                )
              }
            },
            {
              prop: 'gdCount',
              label: '数量',
              width: 180,
              render: (h, scope) =>
                (scope.row._edit && scope.row['pricingMode'] === 1) ? (
                <el-input
                  style='width: 100px'
                  maxlength={10}
                  v-model={scope.row[scope.column.property]}
                  onInput={(val) =>
                    (scope.row[scope.column.property] = val
                      .replace(/[^\d.]/g, '')
                      .replace(/^0\d+|^\./g, '')
                      .replace(/\.{2,}/g, '.')
                      .replace('.', '$#$')
                      .replace(/\./g, '')
                      .replace('$#$', '.')
                      .replace(/^(.*\..{2}).*$/, '$1'))
                  }
                  size='mini'
                />
                  ) : (
                <span>{scope.row[scope.column.property]}</span>
              )
            },
            {
              label: '操作',
              width: '150px',
              fixed: 'right',
              render: (h, scope, $index) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <div>
                      <el-link
                        type='primary'
                        underline={false}
                        size='mini'
                        onClick={() => this.handleSave(scope)}
                      >
                        保存
                      </el-link>
                      <el-link
                        type='primary'
                        underline={false}
                        size='mini'
                        onClick={() => this.handleDel(scope)}
                      >
                        删除
                      </el-link>
                    </div>
                  ) : (
                    <div>
                      <el-link
                        type='primary'
                        underline={false}
                        size='mini'
                        onClick={() => this.handleEdit(scope)}
                      >
                        编辑
                      </el-link>
                      <el-link
                        type='primary'
                        underline={false}
                        size='mini'
                        onClick={() => this.handleDel(scope)}
                      >
                        删除
                      </el-link>
                    </div>
                  )}
                </div>
                )
              }
            }
          ],
          data: [],
          defaultData: []
        },
        transStatusMap: [
          { value: 1, desc: '重', key: 'HEAVY' },
          { value: 2, desc: '空', key: 'LIGHT' },
          { value: 3, desc: '回收', key: 'RECYCLE' },
          { value: 4, desc: '故障', key: 'BROKEN' },
          { value: 5, desc: '已损坏', key: 'CORRUPT' },
          { value: 6, desc: '正常', key: 'NORMAL' },
          { value: 7, desc: '报废', key: 'SCRAPPED' },
          { value: 8, desc: '过期', key: 'EXPIRED' },
          { value: 9, desc: '问题重瓶', key: 'QUEHEAVY' },
          { value: 10, desc: '漏气', key: 'GAS_LEAK' },
          { value: 11, desc: '欠重', key: 'WEIGHT_SHORTAGE' },
          { value: 12, desc: '其他', key: 'OTHER' }
        ],
        type: 1
      }
    },
    computed: {
      ...mapGetters([
        'userInfo', 'corpSettingData'
      ])
    },
    watch: {
      'tableRightData.data': {
        handler(newVal, oldVal) {
          // console.log('newVal', newVal)
          // console.log('oldVal', oldVal)
          // console.log(this.gdStatusMap)

          if (newVal.length && newVal.every(item => item._edit === false)) {
            this.sumObj = []
            this.gdStatusMap.forEach(item => {
              const obj = {
                name: item.desc,
                sum: 0
              }
              const values1 = newVal.map(i => { // 空瓶
                if (i.gdStatus === item.value) {
                  return Number(i.gdCount)
                } else {
                  return 0
                }
              })
              obj.sum = values1.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }) || 0
              this.sumObj.push(obj)
            })
            this.allSum = 0
            this.sumObj.forEach(item => {
              this.allSum += item.sum
            })
          }
        },
        deep: true,
        immediate: true
      }
    },
    created() {
      if (this.userInfo.showRN === JINJIANG) {
        this.rules.targetStoreId[0].required = false
      }
    },
    methods: {
      open() {
        this.leftStoreMap = this.storeMap
        this.rightStoreMap = this.storageStoreMap
        this.getGoodsList()
        if (this.leftStoreMap.find(item => item.reId === this.userInfo.orgId)) {
          this.temp.storeId = this.leftStoreMap.find(item => item.reId === this.userInfo.orgId).storeId || ''
          this.temp.storeName = this.leftStoreMap.find(item => item.reId === this.userInfo.orgId).storeName || ''
          this.temp.storeType = this.leftStoreMap.find(item => item.reId === this.userInfo.orgId).reType || ''
        }

        return new Promise((resolve) => {
          this.resolve = resolve
          this.visible = true
        })
      },
      // 选择商品
      tableLeftChange(row) {
        if (!row) {
          return
        }
        // console.log('row', row)
        const obj = {
          gtId: this.goodsData.gtId,
          gtSNNo: this.goodsData.gtSNNo,
          gtName: this.goodsData.gtName,
          goodsCode: row.goodsCode,
          goodsName: row.goodsName,
          goodsSpec: row.specName,
          specCode: row.specCode,
          unitId: row.unitId,
          unitName: row.unitName,
          tempGdStatus: row.gdStatus,
          goodsId: row.goodsId,
          gtFlag: this.goodsData.gtFlag,
          pricingMode: row.pricingMode,
          gdStatus: '', // 状态
          gdCount: '', // 数量
          netWeight: '', // 重量
          remark: '',
          _edit: true, // 是否编辑
          gdStatusMap: []
        }
        // console.log('obj', obj)
        // 为每行数据添加可供选择的状态
        obj.gdStatusMap = this.setGdStatusMap(obj)
        // 把当前的数据放在右边列表
        this.tableRightData.data.push(obj)
        // console.log('增加后的数据', this.tableRightData.data)
      },
      // 商品分类
      async getGoodsList() {
        const res = await goodsTypeQueryAllList()
        const item = res.data.find(item => item.gtFlag === 2)
        this.currentChange(item)
      },
      // 商品分类事件
      async currentChange(current) {
        this.goodsData = current
        const res = await goodsSortList({
          gtId: current.gtId,
          pageIndex: 1,
          pageSize: 999
        })
        if (this.corpSettingData.sp3 >> 6 & 0x01) {
          const list = res.data.rows.filter(item => {
            if (!item.options) {
              return true
            }
            if (item.options >> 1 & 0x01) {
              return false
            }
            if (item.options >> 2 & 0x01) {
              return false
            }
            return true
          })
          // console.log('list', list)
          this.tableLeftData.data = list
        } else {
          this.tableLeftData.data = res.data.rows
        }
      },
      setGdStatusMap(row) {
        if (this.corpSettingData.sp3 >> 6 & 0x01) {
          if (row.pricingMode === 2) {
            return [{ value: 6, desc: '正常' }]
          } else {
            const datas = this.transStatusMap
            if (row.tempGdStatus) {
              const realItems = []
              for (var i in datas) {
                const item = datas[i]
                if ((row.tempGdStatus & 1 << item.value) > 0) {
                  realItems.push(item)
                }
              }
              return realItems
            } else {
              return datas
            }
          }
        } else {
          if (row.gtFlag === 3 || row.pricingMode === 2) {
            return [{ value: 6, desc: '正常' }]
          } else if (row.gtFlag <= 2) {
            const datas = this.transStatusMap
            if (row.tempGdStatus) {
              const realItems = []
              // eslint-disable-next-line no-redeclare
              for (var i in datas) {
                const item = datas[i]
                if ((row.tempGdStatus & 1 << item.value) > 0) {
                  realItems.push(item)
                }
              }
              console.log('realItems', realItems)
              return realItems
            } else {
              return datas
            }
          }
        }
      },
      exchange() {
        if (this.temp.targetStoreId && this.temp.storeId) {
          const num1 = this.temp.targetStoreId
          const num2 = this.temp.storeId
          this.inChange(num2)
          this.outChange(num1)
          const array1 = JSON.parse(JSON.stringify(this.rightStoreMap))
          this.rightStoreMap = JSON.parse(JSON.stringify(this.leftStoreMap))
          this.leftStoreMap = JSON.parse(JSON.stringify(array1))
        }
      },
      handleEdit(scope) {
        console.log(scope)
        console.log(this.tableRightData.data[scope.$index])
        this.$set(scope.row, '_edit', true)
        // this.$set(this.tableRightData.data[scope.$index], '_edit', true)
      },
      // 保存
      async handleSave(scope) {
        // console.log('scope', scope)
        if (!scope.row.gdStatus || !scope.row.gdCount) {
          this.$message.warning('请完善出库商品信息')
          return
        }
        // 过滤重复增加该商品
        var flag = 0
        if (this.tableRightData.data.length) {
          const list = JSON.parse(JSON.stringify(this.tableRightData.data))
          flag = this.tableRightData.data.some((e) => list.filter((e1) => e1.goodsId === e.goodsId && e1.gdStatus === e.gdStatus).length > 1)
        }
        let repetitionItem = {}
        await this.tableRightData.data.forEach(item => {
          this.tableRightData.data.forEach(i => {
            if (item.goodsId === i.goodsId && item.gdStatus === i.gdStatus) {
              repetitionItem = item
            }
          })
        })
        if (flag) {
          this.$message({
            type: 'warning',
            message: `${repetitionItem.goodsName}（${formatColumnMap(
              repetitionItem.gdStatusMap,
              'value',
              repetitionItem.gdStatus,
              'desc'
            )}）商品已存在`
          })
          return
        }
        this.$set(scope.row, '_edit', false)
        this.$set(
          this.tableRightData.defaultData,
          scope.$index,
          JSON.parse(JSON.stringify(scope.row))
        )
      },
      handleCancle(scope) {
        this.$set(
          this.tableRightData.data,
          scope.$index,
          JSON.parse(JSON.stringify(this.tableRightData.defaultData[scope.$index]))
        )
      },
      handleDel(scope) {
        const row = this.tableRightData.data
        const defaultRow = this.tableRightData.defaultData
        this.$delete(row, scope.$index)
        this.$delete(defaultRow, scope.$index)
      },
      save() {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            if (this.temp.targetStoreId === this.temp.storeId) {
              this.$message({
                type: 'error',
                message: `调出仓库和调入仓库不能相同`
              })
              return
            }

            if (!this.tableRightData.data.length) {
              this.$message({
                type: 'error',
                message: `请添加出库商品`
              })
              return
            }
            if (!this.tableRightData.data.every(item => item._edit === false)) {
              this.$message({
                type: 'error',
                message: `请完成出库商品的编辑`
              })
              return
            }
            // const params = {
            //   ...this.temp,
            //   detailList: this.tableRightData.data
            // }
            // const res = await addStockOutBill(params)
            // if (res.success) {
            //   this.$message({
            //     message: '操作成功！',
            //     type: 'success'
            //   })
            //   this.visible = false
            //   // 更新列表
            //   this.$emit('upDdataTable')
            // }
            this.add()
          } else {
            return false
          }
        })
      },
      async add() {
        const params = {
          ...this.temp,
          detailList: this.tableRightData.data
        }
        const res = await addStockOutBill(params)
        if (res.success) {
          this.$message({
            message: '操作成功！',
            type: 'success'
          })
          this.visible = false
          // 更新列表
          this.$emit('upDdataTable')
        }
      },
      // 车辆参数处理
      truckChange(val) {
        const arr = this.truckMap.find((l) => l.truckId === val)
        this.$set(this.temp, 'carNumber', arr.truckCode)
      },
      // 处理司机
      driverChange(val) {
        if (val) {
          const arr = this.driverMap.find((l) => l.userId === val)
          this.$set(this.temp, 'operator', arr.userName)
          this.$set(this.temp, 'operatorId', arr.userId)
        } else {
          this.$set(this.temp, 'operator', '')
          this.$set(this.temp, 'operatorId', '')
        }
      },
      // 处理仓库数据
      outChange(val) {
        if (val) {
          const arr = this.leftStoreMap.find((l) => l.storeId === val)
          this.$set(this.temp, 'storeId', arr.storeId)
          this.$set(this.temp, 'storeName', arr.storeName)
          this.$set(this.temp, 'storeType', arr.reType)
        } else {
          this.$set(this.temp, 'storeId', '')
          this.$set(this.temp, 'storeName', '')
          this.$set(this.temp, 'storeType', '')
        }
        this.$forceUpdate()
      },
      inChange(val) {
        if (val) {
          const arr = this.rightStoreMap.find((l) => l.storeId === val)
          this.$set(this.temp, 'targetStoreId', arr.storeId)
          this.$set(this.temp, 'targetStoreName', arr.storeName)
          this.$set(this.temp, 'targetStoreType', arr.reType)
        } else {
          this.$set(this.temp, 'targetStoreId', '')
          this.$set(this.temp, 'targetStoreName', '')
          this.$set(this.temp, 'targetStoreType', '')
        }
        this.$forceUpdate()
      },
      reset() {
        this.visible = false
        this.goodsName = ''
        this.temp = {
          stockOutType: 1,
          storeId: '',
          targetStoreId: '',
          carNumber: '',
          operatorId: '',
          remark: ''
        }
        this.sumObj = []
        this.allSum = 0
        this.leftStoreMap = []
        this.rightStoreMap = []
        this.goodsData = {}
        this.lbTableRightwidth = 14
        this.tableRightData.data = []
        this.tableRightData.defaultData = []
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.so {
  padding: 10px;
  border: 1px solid #dfdfdf;
}
.leftTree {
  height: 50vh;
}
.aside.open {
  width: auto;
}
.leftTable {
  height: 50vh;
  overflow-y: auto;
}
.rightTable {
  width: 100%;
}
.total {
  margin-top: 10px;
  font-size: 18px;
  font-weight: 800;
  color: #F00;
}
</style>
